import cv2
import numpy as np

def normalize_image(img):
    # 将图像转换为float32类型
    img = img.astype(np.float32)
    # 将图像归一化到范围[0, 1]
    img_normalized = (img - np.min(img)) / (np.max(img) - np.min(img))
    # 转换回uint8类型
    img_normalized = (img_normalized * 255).astype(np.uint8)
    return img_normalized

def main():
    # 加载图像
    image_path = '1.jpg'  # 修改为你的图像路径
    img = cv2.imread(image_path)

    # 定义聚类（区域）数量
    num_clusters = 2

    # 执行图像分割
    reshaped_img = img.reshape((-1, 3))
    reshaped_img = np.float32(reshaped_img)
    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.2)
    _, labels, centers = cv2.kmeans(reshaped_img, num_clusters, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
    labels = labels.reshape(img.shape[0], img.shape[1])

    # 归一化每个分割区域并创建输出图像
    normalized_img = np.zeros_like(img, dtype=np.float32)  # 更改为float32类型
    for i in range(num_clusters):
        # 提取属于当前区域的像素
        segment = np.where(labels == i, 1, 0)
        segment_img = img * np.expand_dims(segment, axis=2)
        # 找到归一化所需的最小和最大像素值
        min_val = np.min(segment_img[segment_img > 0])
        max_val = np.max(segment_img[segment_img > 0])
        # 归一化分割区域
        normalized_segment = (segment_img - min_val) / (max_val - min_val) * 255  # 归一化后乘以255
        cv2.imshow("fenge", normalized_segment)
        cv2.waitKey(0)
        # 将归一化的分割区域添加到输出图像中
        normalized_img += normalized_segment.astype(np.float32)  # 确保数据类型为float32

    # 将输出图像转换为uint8类型
    normalized_img = normalized_img.astype(np.uint8)

    # 显示和保存输出图像
    cv2.imshow('归一化图像', normalized_img)
    cv2.imwrite('output_normalized_image.jpg', normalized_img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()
